package main

import (
	"fmt"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"log"
	"math/rand"
	"net/http"
	"time"
)

// step1:初始一个counter, with help string
func counter() {
	var pushCounter = prometheus.NewCounter(prometheus.CounterOpts{
		Name: "repository_pushes",
		Help: "Number of pushes to external repository.",
	})

	//setp2： 注册容器
	err := prometheus.Register(pushCounter)
	if err != nil {
		fmt.Println("Push counter couldn't be registered AGAIN, no counting will happen:", err)
		return
	}

	for {
		pushCounter.Inc()
		time.Sleep(1 * time.Second)
	}
}

func counterVec() {
	httpReqs := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "http_requests_total",
			Help: "How many HTTP requests processed, partitioned by status code and HTTP method.",
		},
		[]string{"code", "method"},
	)

	//step2:注册容器
	prometheus.MustRegister(httpReqs)

	// step3: 生产数据
	codes := []string{"200", "300", "400"}
	methods := []string{"GET", "POST", "PUT"}
	for {
		i := rand.Int() % 3
		j := rand.Int() % 3
		m := httpReqs.WithLabelValues(codes[i], methods[j])
		m.Inc()
		time.Sleep(100 * time.Millisecond)
	}
}

func main() {
	go counter()
	go counterVec()

	http.Handle("/metrics", promhttp.Handler())
	log.Fatal(http.ListenAndServe(":8080", nil))
}
